import soundfile as sf
import matplotlib.pyplot as plt
from scipy import signal
import numpy as np
import samplerate
import librosa

def plot_signal(audio_data, title=None):
    plt.figure(figsize=(12, 3.5), dpi=300)
    plt.plot(audio_data, linewidth=1)
    plt.title(title,fontsize = 16)
    plt.tick_params(labelsize=12)
    plt.grid()
    plt.show()

def band_pass_filter(original_signal, order, fc1,fc2, fs):
    b, a = signal.butter(N=order, Wn=[2*fc1/fs,2*fc2/fs], btype='bandpass')
    new_signal = signal.lfilter(b, a, original_signal)
    return new_signal

audio_path = 'test.wav'
# segment_length = 2  # 秒
# overlap = 1000  # 50%
audio_data, fs = librosa.load(audio_path, sr=2000)
plot_signal(audio_data, title='Init Filter')
print(type(audio_data))
print("原始音频数据点数：", audio_data.shape, "采样率：", fs)
audio_data = band_pass_filter(audio_data, 2, 25, 400, fs)
plot_signal(audio_data, title='After Filter')
print(len(audio_data))
down_sample_audio_data = samplerate.resample(audio_data.T, 1000 / fs, converter_type='sinc_best').T
plot_signal(down_sample_audio_data, title='Down_sampled')
print(len(down_sample_audio_data))
down_sample_audio_data = down_sample_audio_data / np.max(np.abs(down_sample_audio_data))
plot_signal(down_sample_audio_data, title='Normalized')
print(len(down_sample_audio_data))
# point = int(fs * (segment_length - overlap / 1000))
# # num_segments = 1 + (len(audio_data) - segment_length * fs) //
# num_segments = len(audio_data) // point - 1
# for i in range(num_segments):
#     start = i * point
#     end = start + segment_length * fs
#     segment = audio_data[start:end]
#     sf.write(f'./audio_cut/{audio_path}_{i}.wav', segment, fs)

time_segment = 2
overlap = 1000
change_sr = 1000
cut_point = int(change_sr * (time_segment - overlap / 1000))
cut_num = len(down_sample_audio_data)//cut_point - 1
for i in range(cut_num):
    start = cut_point*i
    end = cut_point*i+time_segment*change_sr
    segment = audio_data[start:end]
    sf.write(f'./audio_cut/c_{i}.wav', segment, change_sr)

audio_data, fs = librosa.load('./audio_cut/c_1.wav', sr=None)
print(fs)